using Engine;
using Engine.Graphics;
using Game;

namespace SCIENEW {
    public class FluidWidget : CanvasWidget {
        public int m_fluidValue;
        public float m_relativeVolume;

        public override void Draw(DrawContext dc) {
            base.Draw(dc);

            Fluid fluid = FluidsManager.GetFluid(m_fluidValue);

            if(fluid == null || m_relativeVolume <= 0) return;

            Matrix m = GlobalTransform;
            Vector2 v = Vector2.Zero;
            var v2 = new Vector2(ActualSize.X, 0);
            Vector2 v3 = ActualSize;
            var v4 = new Vector2(0f, ActualSize.Y);
            v += new Vector2(0, ((1 - m_relativeVolume) / 1) * Size.Y);
            v2 += new Vector2(0, ((1 - m_relativeVolume) / 1) * Size.Y);
            Vector2.Transform(ref v, ref m, out Vector2 result);
            Vector2.Transform(ref v2, ref m, out Vector2 result2);
            Vector2.Transform(ref v3, ref m, out Vector2 result3);
            Vector2.Transform(ref v4, ref m, out Vector2 result4);
            Color color = fluid.GetColor(m_fluidValue) * GlobalColorTransform;
            if (color.A != 0) {
                TexturedBatch2D texturedBatch2D = dc.PrimitivesRenderer2D.TexturedBatch(fluid.GetTexture(m_fluidValue), useAlphaTest: true, 1, DepthStencilState.None, null, null, SamplerState.PointWrap);
                Vector2 waterSlotsPos = Vector2.Zero;//材质水格子的起始点
                float waterSlotsWidth = 1f / fluid.GetTextureSubdivision(m_fluidValue);//材质水格子的宽度
                float hDw = ActualSize.Y * m_relativeVolume / ActualSize.X;

                Vector2 waterPos0 = waterSlotsPos;
                Vector2 waterPos1 = waterSlotsPos + Vector2.UnitX * waterSlotsWidth;
                Vector2 waterPos2 = waterSlotsPos + Vector2.One * new Vector2(waterSlotsWidth, waterSlotsWidth * hDw);
                Vector2 waterPos3 = waterSlotsPos + Vector2.UnitY * waterSlotsWidth * hDw;
                //材质格子偏移
                int texSlotIndex = fluid.GetTextureSlot(m_fluidValue);
                Vector2 texSlotOffset = new (waterSlotsWidth * (texSlotIndex % fluid.GetTextureSubdivision(m_fluidValue)), waterSlotsWidth * (texSlotIndex / fluid.GetTextureSubdivision(m_fluidValue)));
                waterPos0 += texSlotOffset;
                waterPos1 += texSlotOffset;
                waterPos2 += texSlotOffset;
                waterPos3 += texSlotOffset;
                texturedBatch2D.QueueQuad(result, result2, result3, result4, 0, waterPos0, waterPos1, waterPos2, waterPos3, color);
            }
        }

        public override void MeasureOverride(Vector2 parentAvailableSize) {
            IsDrawRequired = true;
            DesiredSize = Size;
        }
    }
}